importScripts("./js/quote/md5.js");

var version ="DEF's_Green_static_doc",
  cacheNames = [version];

this.onmessage=function(msg){

}
this.oninstall=function(e){
    console.log(e);
    e.waitUntil(
        caches.open(version).then(function(cache){
            console.log(version+" install");  
            return cache.addAll([
                ".",
                "./index.html",
                "./css/basics.css",
                "./js/basics/basics.js",
                "./js/ControlLib/CtrlLib.js",
                "./page/index.js",
                "./page/EXctrl.xml",
                "./page/EXctrl.js",
                "./page/EXctrl.css",
                "./page/page.xml",
                "./page/page.js",
                "./page/page.css",
                "./img/logo.svg",
                "./img/iconSprites.svg"
            ]);
        }).then(function(){
            self.skipWaiting();
        })
    )
}
this.activate=function(e){
  e.waitUntil(
    caches.keys().then(keys => {
      return Promise.all[keys.map(key => {
        if (!cacheNames.includes(key)) {
          console.log(key);
          return caches.delete(key); // 删除不在白名单中的 Cache Stroage
        }
      })]
    })
  );
}

this.addEventListener('fetch', function (event) {
        event.respondWith(
      caches.match(event.request).then(res => {
        return res ||
          fetch(event.request)
            .then(responese => {
              const responeseClone = responese.clone();
              caches.open(version).then(cache => {
                cache.put(event.request, responeseClone);
              })
              return responese;
            })
            .catch(err => {
              console.log(err);
              return res;
            });
      })
    )
  });
// this.addEventListener('fetch', function(event) {
//   event.respondWith(
//     caches.match(event.request).then(function(resp) {
//       return fetch(event.request).then(function(response) {
//         return caches.open('v1').then(function(cache) {
//           cache.put(event.request, response.clone());
//           return response;
//         }).catch(function(){
//           return resp;
//         })
//       });
//     })
//   );
// });